#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/types.h>
# include <sys/socket.h>
# include "proto.h"

#define  IPSTRSIZE 40


int main(){

    int sd;
    struct sockaddr_in laddr, raddr; 
    struct msg_st rbuf;
    socklen_t raddr_len;
    char ipstr[IPSTRSIZE];

    sd = socket (AF_INET, SOCK_DGRAM, 0/*IPPROTO_UDP*/) ;     //创建socket  AF_INET域 报式 0代表默认 
    if(sd < 0 ){
        perror("socket ()");
        exit(1);
    }
    laddr.sin_family = AF_INET;
    laddr.sin_port = htons(atoi(RCVPORT));
    inet_pton (AF_INET,"0.0.0.0",&laddr.sin_addr);  //将点分式IP字符串转换为大整数
    
    if(bind (sd, (void *)&laddr, sizeof (laddr)) <0) {   //绑定 
        perror("bind()");
        exit(1);

    }     
    int val = 1;
    if(setsockopt (sd, SOL_SOCKET, SO_BROADCAST, &val, sizeof (val))<0){
        perror ("setsockopt () ");
        exit(1);
    }
      
    raddr_len = sizeof (raddr)     /**非常重要，要对对端地址大小进行初始化，否则第一次会出错**/
    while(1){
        recvfrom (sd,&rbuf,sizeof(rbuf),0,(woid *)&raddr,raddr_len);  //接收消息
        inet_ntop (AF_INET, & raddr. sin_addr, ipstr, IPSTRSIZE); 
        printf ("---MESSAGE FROM %s:%d---n", ipstr, ntohs (raddr. sn_port));
        printf ("NAME = %s\n", rbuf. name); 
        printf ("MATH = %d\n", ntohl (rbuf. math)); 
        printf ("CHINESE = %d\n", ntohl (rbuf. chinese));
        

    }
    


    close();//关闭
    exit(0);
}